package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @program: day0513-week3
 * @ClassName MyFilter
 * @description:
 * @author: 段阳
 * @create: 2024-05-13 09:22
 **/
@Configuration
public class MyFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getPath().toString();
        String ip = request.getRemoteAddress().getAddress().toString();
        if (ip.equals("192.168.6.128")){
           return chain.filter(exchange);
        }
        if (url.contains("/login")){
            return chain.filter(exchange);
        }
        if (url.contains("/list")){
            return chain.filter(exchange);
        }
        if (url.contains("/upload")){
            return chain.filter(exchange);
        }
        if (url.contains("/vCode")){
            return chain.filter(exchange);
        }
        //上面放行登录与列表，其余操作需要登录后进行！
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        Claims claims = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody();
        Integer id = claims.get("id", Integer.class);
        String tokenKey = "USER-TOKEN-"+id;
        String RToken = stringRedisTemplate.opsForValue().get(tokenKey);
        if (StringUtils.isBlank(RToken)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        if (!token.equals(RToken)){
            response.setStatusCode(HttpStatus.PAYMENT_REQUIRED);
            return response.setComplete();
        }
        Long expire = stringRedisTemplate.getExpire(tokenKey, TimeUnit.MINUTES);
        if (expire<10){
            stringRedisTemplate.expire(tokenKey,30,TimeUnit.MINUTES);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}